﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using ESF.General;
using Microsoft.Ajax.Utilities;

#endregion


namespace ESF.Web.Handlers
{
	public class JSCompression : IHttpHandler
	{
		#region Metodos de IHttpHandler

		public bool IsReusable
		{
			get { return false; }
		}

		public void ProcessRequest(HttpContext pContext)
		{
			string fileName;
			string contents;
			string eTag;

			Minifier minifier;

			FileInfo fileInfo;

						
			fileName = pContext.Request.PhysicalPath;

			ModuleHandlerHelper.AddESFDescriptionHeader(pContext, "JSCompressed"); 
			

			if (ModuleHandlerHelper.GeneratedResponse_SetETagCacheIs304File(pContext, fileName, null, 60, out fileInfo, out eTag))
			{
				return;
			}


			if (HttpContext.Current.Application["JSCompressed_" + eTag] == null)
			{
				HttpContext.Current.Trace.Write ("Nuevo: JSCompressed_" + eTag);

				contents = File.ReadAllText(fileName);

				if (!Path.GetFileNameWithoutExtension(fileName).ToUpper().StartsWith("jquery"))
				{	
					minifier = new Minifier();

					contents = minifier.MinifyJavaScript (contents);
				}
				
				HttpContext.Current.Application.Add("JSCompressed_" + eTag, contents);

				HttpContext.Current.Trace.Write("Guardado: JSCompressed_" + eTag);
			}
			else
			{
				HttpContext.Current.Trace.Write("Leido: JSCompressed_" + eTag);

				contents = HttpContext.Current.Application["JSCompressed_" + eTag] as string;
			}

			
			ModuleHandlerHelper.AddZipFilter(pContext);

			pContext.Response.Write (contents);
		}

		#endregion
	}
}
